<!-- 供给负荷 -->
<template>
  <div class="supply-load-wrap">
    <div class="top_wrap">
      <px-form ref="queryRef" class="custom-form-ui inspection-form" :model="queryParams" :inline="true" label-width="100px">
        <!-- <px-form-item label="时间维度" prop="dataFormat" style="width: 340px">
          <px-radio-group v-model="queryParams.queryTimeType" style="margin-left: 10px" @change="handleRadioChange">
            <px-radio size="small" label="hour">小时</px-radio>
            <px-radio size="small" label="day">日</px-radio>
            <px-radio size="small" label="month">月</px-radio>
            <px-radio size="small" label="year">年</px-radio>
          </px-radio-group>
        </px-form-item> -->
        <px-form-item label="时间范围" style="width: 430px">
          <!-- <px-date-picker
            v-if="queryParams.queryTimeType === 'hour'"
            v-model="dateRange"
            type="datetimerange"
            range-separator="-"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          /> -->
          <px-date-picker
            v-if="queryParams.queryTimeType === 'day'"
            v-model="dateRange"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
          <px-date-picker
            v-if="queryParams.queryTimeType === 'month'"
            v-model="dateRange"
            type="monthrange"
            value-format="YYYY-MM"
            range-separator="-"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
          />
          <div v-if="queryParams.queryTimeType === 'year'">
            <yearPicker ref="statisticPicker" :labelWidth="0" labelText="" :initYear="dateValue" @updateTimeRange="updateStatisticYear" />
          </div>
        </px-form-item>
        <!-- <px-form-item label="厂区">
          <px-select v-model="queryParams.factory" clearable placeholder="请选择层级">
            <px-option v-for="item in systemList" :key="item.value" :label="item.name" :value="item.value" />
          </px-select>
        </px-form-item> -->
        <px-button type="primary" @click="handleQuery">搜索</px-button>
        <px-button @click="resetQuery">重置</px-button>
      </px-form>
    </div>
    <div v-loading="pageLoading" class="content-wrap">
      <px-row :gutter="16">
        <px-col :span="12">
          <div class="table-content">
            <modelTitle :title="'负荷列表'" />
            <btnImageAndData
              v-has="'ALL_ENERGY_SUPPLY_LOAD_DOWNLOAD'"
              :exportImage="Boolean(false)"
              class="export-btn"
              @exportChange="val => handlerExport(val, 'table', '')"
            />
            <px-table v-loading="tableLoading" :data="tableData" stripe size="small" border class="table-wrap">
              <px-table-column type="index" label="序号" fixed width="55" align="center" />
              <px-table-column prop="energyName" label="能源" min-width="120" show-overflow-tooltip />
              <px-table-column prop="energyUnit" label="单位" min-width="80" show-overflow-tooltip />
              <px-table-column prop="maxSupply" label="最大供给量" min-width="80" show-overflow-tooltip />
              <px-table-column prop="realMaxLoad" label="实际最高负荷" min-width="160" show-overflow-tooltip />
              <px-table-column prop="maxLoadRate" label="最高负荷率" min-width="120" show-overflow-tooltip />
              <!-- <px-table-column prop="loadStatus" label="负荷状态" min-width="120" show-overflow-tooltip /> -->
            </px-table>
            <!-- <px-button v-has="'ALL_ENERGY_SUPPLY_LOAD_DOWNLOAD'" class="export-btn" @click="handlerExport('table')">导出</px-button> -->
          </div>
        </px-col>
        <px-col :span="12">
          <div class="left-wrap">
            <div class="left-top">
              <div class="left-top-top">
                <modelTitle :title="'供给负荷率'" />
                <px-select v-model="energyCode" placeholder="请选择" size="small" class="select-wrap" @change="handleSelectChange">
                  <px-option v-for="item in selectOption" :key="item.value" :label="item.label" :value="item.value" />
                </px-select>
                <btnImageAndData
                  v-has="'ALL_ENERGY_SUPPLY_LOAD_DOWNLOAD'"
                  class="export-btn"
                  @exportChange="val => handlerExport(val, 'line', 'chartLineRef')"
                />
                <!-- <px-button v-has="'ALL_ENERGY_SUPPLY_LOAD_DOWNLOAD'" class="export-btn" @click="handlerExport('line')">导出</px-button> -->
              </div>
              <div ref="chartLineRef" class="left-top-btm" />
            </div>
            <div class="left-btm">
              <modelTitle :title="'供给负荷热力图'" />
              <div ref="loadHeatMapRef" class="left-btm-btm" />
              <btnImageAndData
                v-has="'ALL_ENERGY_SUPPLY_LOAD_DOWNLOAD'"
                class="export-btn"
                @exportChange="val => handlerExport(val, 'heat', 'loadHeatMapRef')"
              />
              <!-- <px-button v-has="'ALL_ENERGY_SUPPLY_LOAD_DOWNLOAD'" class="export-btn" @click="handlerExport('heat')">导出</px-button> -->
            </div>
          </div>
        </px-col>
      </px-row>
    </div>
  </div>
</template>
<script setup>
import { ref, toRefs, reactive, onMounted, getCurrentInstance } from "vue";
import yearPicker from "@/views/common/energy/components/yearPicker.vue";
import * as echarts from "echarts";
import { getListLoadStateAPI, getBrokenLineDataAPI, getLineParameterAPI, getHotPowerDiagramAPI } from "@/api/energy/supplyLoad";
import dayjs from "dayjs";
import modelTitle from "@/views/common/components/modelTitle/index.vue";
import btnImageAndData from "@/views/common/energy/components/btnImageAndData/index.vue";

defineOptions({
  name: "ALL_ENERGY_SUPPLY_LOAD"
});

const chartLineRef = ref();
const loadHeatMapRef = ref();
const yearStart = ref("");
const yearEnd = ref("");

// 可选择区间，initYear传参，不传则所有年份有效，小于0判断一下？
const dateValue = ref({
  startYear: `${new Date().getFullYear() - 2}`,
  endYear: `${new Date().getFullYear()}`
});

// 定义数据
const dateRange = ref([]);

const { proxy } = getCurrentInstance();

const state = reactive({
  queryParams: {
    queryTimeType: "month",
    factory: ""
  },
  pageLoading: true,
  tableData: [],
  energyCode: "",
  energyName: "",
  selectOption: [],
  tableLoading: true
});
const { queryParams, pageLoading, tableData, energyCode, selectOption, tableLoading } = toRefs(state);

onMounted(() => {
  initQuery();
  getTableData();
  getLineSelectData();
});

let chartObj = {};
// 获取表格数据
const getTableData = async () => {
  try {
    state.tableLoading = true;
    const { timeNum, startTime, endTime } = getParams();
    const params = {
      periodType: timeNum || 3,
      startTime: startTime || "",
      endTime: endTime || ""
    };
    const res = await getListLoadStateAPI(params);
    if (res?.length) {
      // res?.forEach(item => {
      //   // 市政进线的
      //   if ([1, 2, 3, 4].includes(item.id)) {
      //     item.realMaxLoad = "-";
      //     item.maxLoadRate = "-";
      //   }
      // });
      state.tableData = res;
    } else {
      state.tableData = [];
    }
  } catch (error) {
    console.log(error);
  } finally {
    state.tableLoading = false;
  }
};

// 获取折线图数据
const getLineData = async () => {
  try {
    state.pageLoading = true;
    const { timeNum, startTime, endTime } = getParams();
    const params = {
      periodType: timeNum || 3,
      startTime: startTime || "",
      endTime: endTime || "",
      energyCode: state.energyCode || "",
      energyName: state.energyName || ""
    };
    const res = await getBrokenLineDataAPI(params);
    if (res?.dateAxis?.length) {
      drawLineChart(res);
    }
  } catch (error) {
  } finally {
    state.pageLoading = false;
  }
};

// 画折线图
const drawLineChart = args => {
  let xAxisData = args?.dateAxis || [];
  let seriesData = args?.dataRateAxis?.map(item => item?.replace("%", ""));
  // let name = args?.lineName?.unit || "";
  const options = {
    // toolbox: {
    //   show: true,
    //   feature: {
    //     saveAsImage: {
    //       title: "点击保存为图片"
    //     }
    //   }
    // },
    grid: {
      bottom: "10%"
    },
    tooltip: {
      trigger: "axis",
      formatter: function (params) {
        return params[0].name + "<br/>" + "负荷率：" + params[0].value + "%<br/>";
      }
    },
    xAxis: {
      type: "category",
      data: xAxisData
    },
    yAxis: {
      type: "value",
      name: "负荷率%"
    },
    series: [
      {
        data: seriesData,
        type: "line"
      }
    ]
  };
  let myChart = echarts.init(chartLineRef.value);
  chartObj.chartLineRef = myChart;
  myChart.clear();
  myChart.setOption(options);
};

// 获取热力图数据
const getHeatMapData = async () => {
  try {
    // state.pageLoading = true;
    const { timeNum, startTime, endTime } = getParams();
    const params = {
      periodType: timeNum || 3,
      startTime: startTime || "",
      endTime: endTime || "",
      energyCode: state.energyCode || ""
    };
    const res = await getHotPowerDiagramAPI(params);
    res ? drawHeatMapChart(loadHeatMapRef.value, res) : "";
  } catch (error) {
    console.log(error);
  } finally {
    state.pageLoading = false;
  }
};

// 系统负荷-热力图
const drawHeatMapChart = (dom, obj) => {
  let loadRateAry = [];
  let xyData = [];
  obj?.xyAxisData?.forEach(innerArray => {
    const [first, second, third] = innerArray;
    const parts = third.split("#");
    const newArray = [Number(first), Number(second), Number(parts[1].split("%")[0])];
    xyData.push(newArray);
    if (parts.length > 1) {
      loadRateAry.push(parts[1]);
    }
  });
  let options = {
    tooltip: {
      formatter: function (params) {
        return `时间: ${params.name}-${params.value[1]}<br>负荷率: ${loadRateAry[params?.dataIndex]}`;
      }
    },
    // toolbox: {
    //   show: true,
    //   feature: {
    //     saveAsImage: {
    //       title: "点击保存为图片"
    //     }
    //   }
    // },
    grid: {
      bottom: "10%"
    },
    xAxis: {
      type: "category",
      data: obj?.xaxis || []
    },
    yAxis: {
      type: "category",
      data: obj?.yaxis || []
    },
    visualMap: {
      min: 0,
      max: 1,
      calculable: true,
      realtime: false,
      right: "10",
      bottom: "10",
      inRange: {
        color: ["#313695", "#4575b4", "#74add1", "#abd9e9", "#e0f3f8", "#ffffbf", "#fee090", "#fdae61", "#f46d43", "#d73027", "#a50026"]
      }
    },
    series: [
      {
        name: "Gaussian",
        type: "heatmap",
        data: xyData,
        emphasis: {
          itemStyle: {
            borderColor: "#333",
            borderWidth: 1
          }
        },
        progressive: 1000,
        animation: false
      }
    ]
  };
  let myChart = echarts.init(dom);
  chartObj.loadHeatMapRef = myChart;
  myChart.clear();
  myChart.setOption(options);
};

// 获取折线图下拉选项
const getLineSelectData = async () => {
  try {
    const res = await getLineParameterAPI();
    if (res?.length) {
      state.selectOption = res.map(item => {
        return {
          label: item?.lineName || "",
          value: item?.lineCode || ""
        };
      });
      // let obj = state.selectOption?.find(item => item.label === "GN2");
      let obj = state.selectOption[0];
      state.energyCode = obj.value;
      state.energyName = obj.label;
      getLineData();
      getHeatMapData();
    }
  } catch (error) {}
};

// 开始时间和结束时间，时间类型
const getParams = () => {
  let timeType = state.queryParams.queryTimeType;
  let startTime = "";
  let endTime = "";
  if (timeType === "day") {
    startTime = dateRange.value[0] + " 00:00:00";
    endTime = dateRange.value[1] + " 23:59:59";
  }
  if (timeType === "month") {
    startTime = dateRange.value[0] + "-01 00:00:00";
    // 获取最后一天的日期
    let lastDay = dayjs(dateRange.value[1]).endOf("month").format("YYYY-MM-DD");
    endTime = lastDay + " 23:59:59";
  }
  if (timeType === "year") {
    startTime = yearStart.value;
    endTime = yearEnd.value;
  }

  let timeObj = {
    hour: 1,
    day: 2,
    month: 3,
    year: 4
  };
  let timeNum = timeObj[timeType] || 3;
  return {
    startTime,
    endTime,
    timeType,
    timeNum
  };
};

// 初始化查询条件
const initQuery = () => {
  state.queryParams.queryTimeType = "month";
  // 设置时间的默认值
  setTimeDefaultValue(state.queryParams.queryTimeType);
};
// 根据时间类型不同，设置不同的默认值
const setTimeDefaultValue = val => {
  switch (val) {
    case "day":
      dateRange.value = [dayjs().startOf("month").format("YYYY-MM-DD"), dayjs().endOf("month").format("YYYY-MM-DD")];
      break;
    case "month":
      let startDate = dayjs().subtract(12, "month").format("YYYY-MM");
      let endDate = dayjs().subtract(1, "month").format("YYYY-MM");
      dateRange.value = [startDate, endDate];
      break;
    case "year":
      let yearE = new Date().getFullYear();
      yearStart.value = `${yearE - 2}-01-01 00:00:00`;
      yearEnd.value = `${yearE}-12-31 23:59:59`;
      break;
    default:
      break;
  }
};
// 切换年月日
const handleRadioChange = val => {
  // 设置时间的默认值
  setTimeDefaultValue(val);
  handleQuery();
};
// 选完/输入完成的回调
const updateStatisticYear = (startYear, endYear) => {
  dateRange.value = [startYear ? startYear.toString() : "", endYear ? endYear.toString() : ""];
  yearStart.value = `${startYear}-01-01 00:00:00`;
  yearEnd.value = `${endYear}-12-31 23:59:59`;
  // 刷新页面
  handleQuery();
};

// 查询按钮
const handleQuery = () => {
  getTableData();
  getLineData();
  getHeatMapData();
};
// 重置按钮
const resetQuery = () => {
  initQuery();
  handleQuery();
};
// 导出按钮
const handlerExport = (val1, val2, val3) => {
  const { startTime, endTime, timeNum } = getParams();
  if (val1 === "data") {
    let params = {
      periodType: timeNum,
      startTime: startTime,
      endTime: endTime
    };
    if (val2 === "table") {
      proxy.download("post", "/energy/supplyLoad/exportLoadState", params, "供给负荷表格.xlsx");
    } else if (val2 === "line") {
      params.energyCode = state.energyCode;
      params.energyName = state.energyName;
      proxy.download("post", "/energy/supplyLoad/exportBrokenLine", params, "供给负荷折线图.xlsx");
    } else {
      params.energyCode = state.energyCode;
      proxy.download("post", "/energy/supplyLoad/exportHotPowerDiagram", params, "供给负荷热力图.xlsx");
    }
  } else {
    let myChart = chartObj[val3];
    if (!myChart) return;
    // 获取Base64图片数据
    const imgUrl = myChart.getDataURL({
      type: "png",
      pixelRatio: 2,
      backgroundColor: "#fff"
    });
    // 创建并触发下载链接
    const link = document.createElement("a");
    link.href = imgUrl;
    link.download = "chart.png";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
};
// 折线图下拉框选择变化
const handleSelectChange = val => {
  let result = state.selectOption?.find(item => item?.value === val);
  state.energyName = result?.label || "";
  getLineData();
  getHeatMapData();
};
</script>

<style lang="scss" scoped>
.supply-load-wrap {
  .top_wrap {
    display: flex;
    width: 100%;
    height: auto;
    padding: 16px 24px;
    margin-bottom: 16px;
    line-height: 44px;
    background: #fff;
    border-radius: 4px;

    .query_top {
      display: flex;

      /*
      * tab样式
      */
      .tabSwitch {
        min-width: 200px;
        padding: 0 5px;
        margin-right: 20px;
        background-color: #f4f4f4;
        border-radius: 4px;

        :deep(.px-radio-button__inner) {
          background-color: #f4f4f4;
          border: none;
        }

        :deep(.is-active) {
          border: none;

          .px-radio-button__inner {
            background-color: var(--px-color-primary);
            border-radius: 4px;
          }
        }
      }
    }

    .select_year {
      display: flex;
      align-items: center;
      justify-content: left;
      margin-right: 20px;
    }

    .px-form-item {
      margin-bottom: 0;
    }
  }

  .content-wrap {
    .table-content {
      position: relative;
      padding: 16px 24px;
      background: #fff;
      border-radius: 4px;
    }

    .export-btn {
      position: absolute;
      top: 16px;
      right: 24px;
    }

    .table-wrap {
      height: calc(100vh - 298px);
      margin-top: 16px;
    }

    .left-wrap {
      display: flex;
      flex-direction: column;
      height: calc(100vh - 218px);
    }

    .left-top {
      position: relative;
      display: flex;
      flex: 1;
      flex-direction: column;
      padding: 16px 24px;
      margin-bottom: 16px;
      background: #fff;
      border-radius: 4px;

      .select-wrap {
        position: absolute;
        top: 16px;
        right: 85px;
      }

      .left-top-top {
        margin-bottom: 16px;
      }

      .left-top-btm {
        flex: 1;
      }
    }

    .left-btm {
      position: relative;
      display: flex;
      flex: 1;
      flex-direction: column;
      padding: 16px 24px;
      background: #fff;
      border-radius: 4px;

      .left-btm-btm {
        flex: 1;
        margin-top: 16px;
      }
    }
  }
}
</style>
